package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {


    @Autowired
    private DeptService deptService;

    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        // 根据最后修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));

        // 使用LambdaQuery来构建查询条件，并返回分页结果
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);

        // 添加部门名称
        List<Emp> emps = page.getRecords();
        emps.forEach(emp -> {
            Dept dept = deptService.getById(emp.getDeptId());
            if (dept != null) {
                emp.setDeptName(dept.getName());
            }
        });

        return new PageResult<>(page.getTotal(), emps);
    }

}
